<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>课程管理</el-breadcrumb-item>
    <el-breadcrumb-item>分类管理</el-breadcrumb-item>
  </el-breadcrumb>
  <div>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="课程分类名称:">
        <el-input v-model="formInline.classifyName" placeholder="请输入课程分类名称" clearable :suffix-icon="Search"
                  @clear="handleClear" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
        <el-button type="primary" @click="addbutton">新增课程分类</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
      </el-form-item>
    </el-form>
  </div>
  <el-table :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
    <el-table-column type="selection" fixed prop="id" label="ID" width="150" />
    <el-table-column prop="id" label="id" width="110" />
    <el-table-column prop="classifyName" label="课程分类名称" width="1100" />
    <el-table-column fixed="right" label="操作" min-width="150">
      <template #default="scope">
        <el-button type="primary" size="small" @click="bianji(scope.row)">编辑</el-button>
        <el-button type="danger" size="small" @click="remove(scope.row.id)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
                 :size="size" :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total"
                 @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  <el-dialog v-model="dialogFormVisible" title="新增课程" width="500">
    <el-form>
      <el-form-item label="分类名称" :label-width="formLabelWidth">
        <el-input v-model="flname" autocomplete="off" placeholder="请输入分类名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="add">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogFormVisible1" title="修改课程" width="500">
    <el-form>
      <el-form-item label="分类名称" :label-width="formLabelWidth">
        <el-input v-model="flname" autocomplete="off" placeholder="请输入分类名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取消</el-button>
        <el-button type="primary" @click="change">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import axios from 'axios'
import { onMounted, reactive, ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from "element-plus";

const flname = ref('')
const currentId = ref(0) // 存储当前编辑的分类ID

const dialogFormVisible = ref(false)
const dialogFormVisible1 = ref(false)

// 删除方法（单个删除）
const remove = (id) => {
  ElMessageBox.confirm(
      '请确认是否删除?',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    axios.delete(`http://localhost:8080/courseclassify/${id}`)
        .then(response => {
          // 根据后端实际返回判断，这里假设code为200表示删除成功，其他情况为删除失败（包含分类下有课程的情况）
          if (response.data.code === 200) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            });
          } else {
            ElMessage({
              type: 'error',
              message: response.data.data || '删除失败',
            });
          }
        })
        .catch(error => {
          console.log(error);
          ElMessage({
            type: 'error',
            message: '请求失败，请稍后再试',
          });
        })
        .finally(() => {
          query();
        });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除',
    });
  });
}

const formInline = reactive({
  id: 0,
  classifyName: "",
  pageSize: 5,
  pageNum: 1,
})
let tableData = ref([])
const selectedRows = ref([]);
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)

// 查询数据方法
const query = () => {
  axios.get(`http://localhost:8080/courseclassify/page?pageSize=${pageSize.value}&pageNum=${currentPage.value}`)
      .then(function (response) {
        tableData.value = response.data.data.list
        total.value = response.data.data.total
      }).catch(function (error) {
    console.log(error);
  }).finally(() => {
    console.log(123)
  });
}

// 新增方法
const add = () => {
  axios.post('http://localhost:8080/courseclassify', {
    id: "",
    classifyName: flname.value
  }).then((response) => {
    if (response.data.code === 200) {
      ElMessage({
        type: 'success',
        message: '新增成功',
      });
    } else {
      ElMessage({
        type: 'error',
        message: '新增失败',
      });
    }
  }).catch(function (error) {
    ElMessage({
      type: 'error',
      message: '新增失败',
    });
    console.log(error);
  }).finally(() => {
    query()
    dialogFormVisible.value = false
  });
}

// 搜索方法
const onSubmit = () => {
  axios.get(
      `http://localhost:8080/courseclassify/page?id=${formInline.id}&classifyName=${formInline.classifyName}&pageSize=${formInline.pageSize}&pageNum=${formInline.pageNum}`
  ).then(function (response) {
    tableData.value = response.data.data.list
    total.value = response.data.data.total
  }).catch(function (error) {
    console.log(error);
  }).finally(() => {
    console.log(123)
  });
}

// 修改方法
const change = () => {
  const requestData = {
    id: currentId.value,
    classifyName: flname.value
  };
  axios.put('http://localhost:8080/courseclassify', requestData, {
    headers: {
      'Content-Type': 'application/json'
    }
  })
      .then(function (response) {
        if (response.data.code === 200) {
          ElMessage({
            type: 'success',
            message: '修改成功',
          });
        } else {
          ElMessage({
            type: 'error',
            message: '修改失败：' + response.data.message,
          });
        }
      })
      .catch(function (error) {
        console.error(error);
        ElMessage({
          type: 'error',
          message: '请求失败，请稍后再试',
        });
      })
      .finally(() => {
        query();
        dialogFormVisible1.value = false;
      });
}

onMounted(() => {
  query()
})

const handleSizeChange = (val) => {
  pageSize.value = val
  query()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  query()
}

const handleSelectionChange = (val) => {
  selectedRows.value = val;
}

// 批量删除方法
const batchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessageBox.alert('至少选择一条数据才能进行删除', {
      confirmButtonText: 'OK',
      callback: (action) => {
        ElMessage({
          type: 'info',
          message: `action: ${action}`,
        })
      },
    })
    return;
  }
  const ids = selectedRows.value.map(row => row.id).join(',');
  try {
    const response = await axios.delete(`http://localhost:8080/courseclassify?ids=${ids}`);
    if (response.data.code === 200) {
      ElMessage({
        type: 'success',
        message: '批量删除成功',
      });
    } else {
      ElMessage({
        type: 'error',
        message: response.data.data || '批量删除失败',
      });
    }
    query();
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '批量删除失败',
    });
    console.error(error);
  }
};

const bianji = (row) => {
  dialogFormVisible1.value = true;
  flname.value = row.classifyName;
  currentId.value = row.id;
}

const addbutton = () => {
  dialogFormVisible.value = true
  flname.value = ""
}

const handleClear = () => {
  query()
}
</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

el-table-column {
  max-height: 150px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-breadcrumb {
  border-bottom: 1px solid #EEEEEE;
  padding-bottom: 15px;
}
</style>